import User from "../models/userModel.js";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";

async function hashPassword(password) {
  return await bcrypt.hash(password, 10);
}

async function validatePassword(plainPassword, hashedPassword) {
  return await bcrypt.compare(plainPassword, hashedPassword);
}

export default class UsersController {
  static async apiAddUser(req, res, next) {
    console.log(req.body);
    try {
      const { username, email, password, role } = req.body;
      const hashedPassword = await hashPassword(password);
      const newUser = new User({
        username: username,
        email: email,
        password: hashedPassword,
        role: role,
      });
      const accessToken = jwt.sign(
        { userId: newUser._id },
        process.env.JWT_SECRET,
        {
          expiresIn: "1d",
        }
      );
      newUser.accessToken = accessToken;
      await newUser.save();
      console.log("add user successfully");
      res.status(200).json({ data: newUser, accessToken });
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  }

  static async apiGetUsers(req, res, next) {
    console.log("apiGetUserscalled");
    try {
      const user = await User.find({});
      console.log(user);
      res.status(200).json(user);
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  }

  static async apiLogin(req, res, next) {
    try {
      const { name, password } = req.body;
      console.log("login: ", name, password);
      const user = await User.findOne({ username: name });
      if (!user) return next(new Error("Email does not exist"));
      const validPassword = await validatePassword(password, user.password);
      if (!validPassword) return res.status(200).json({message: 'password is not correct'})
      const accessToken = jwt.sign(
        { userId: user._id },
        process.env.JWT_SECRET,
        {
          expiresIn: "1d",
        }
      );
      await User.findByIdAndUpdate(user._id, { accessToken });
      res.status(200).json({
        name: user.username,
        email: user.email,
        role: user.role,
        id: user._id,
        accessToken,
      });
    } catch (error) {
      console.log("login error", error);
      next(error);
    }
  }
}
